<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Dict;
use App\Model\DictDatum;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class DictController extends AbstractController
{

    #[GetMapping(path: '/sys/dict')]
    public function list()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $name = $this->request->input('name', '');
        $status = $this->request->input('status', '');
        $list = Dict::query()
            ->when($name, function ($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%');
            })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })->forPage($pageNum, $pageSize)->get();
        $data['searchCount'] = true;
        $data['current'] = (int)$pageNum;
        $data['size'] = (int)$pageSize;
        $data['total'] = Dict::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[RequestMapping(path: '/sys/dict/update', methods: ['PUT'])]
    public function update()
    {
        $dict = $this->request->inputs(['id','name','type','status','remark']);
        try {
            if (!isset($dict['id'])){
                Dict::query()->create($dict);
            }else{
                Dict::query()->updateOrInsert(['id' => $dict['id']], $dict);
            }
            return success();
        }catch (\Throwable $e){
            return fail(201, $e->getMessage());
        }
    }

    #[RequestMapping(path: '/sys/dict/add', methods: ['POST'])]
    public function add()
    {
        $dict = $this->request->inputs(['id','name','type','status','remark']);
        try {
            Dict::query()->create($dict);
            return success();
        }catch (\Throwable $e){
            return fail(201, $e->getMessage());
        }
    }

    #[DeleteMapping(path: '/sys/dict/delete/{ids}')]
    public function delete($ids)
    {
        try {
            $idArr = explode(',', $ids);
            Dict::query()->whereIn('id', $idArr)->delete();
            return success();
        } catch (\Throwable $e) {
            logInfo('delete', $e->getMessage(), 'dictData');
            return fail(201, $e->getMessage());
        }

    }
}
